import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from '@/utils/auth';
import { UserModel } from '@/models/user';

// GET 请求处理器 - 获取收件箱消息
export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const token = request.headers.get('Authorization')?.replace('Bearer ', '');
    if (!token) {
      return NextResponse.json({ error: '未提供认证token' }, { status: 401 });
    }

    const decoded = verifyToken(token);
    if (!decoded) {
      return NextResponse.json({ error: '无效的token' }, { status: 401 });
    }

    const userId = decoded.userId;

    try {
      // 获取简历投递相关的消息
      const resumeSubmissions = await UserModel.query(`
        SELECT 
          rs.id,
          rs.job_post_id,
          rs.applicant_id,
          rs.is_read,
          rs.submitted_at,
          rs.feedback,
          rs.resume_file_path,
          jp.title as job_title,
          jp.company_id,
          jp.created_by as company_contact_id,
          u.username as applicant_username,
          u.avatar as applicant_avatar,
          c.name as company_name,
          c.logo as company_logo,
          'resume_submission' as message_type
        FROM resume_submissions rs
        LEFT JOIN job_positions jp ON rs.job_post_id = jp.id
        LEFT JOIN users u ON rs.applicant_id = u.id
        LEFT JOIN companies c ON jp.company_id = c.id
        WHERE rs.applicant_id = ? OR jp.created_by = ?
        ORDER BY rs.submitted_at DESC
      `, [userId, userId]);

      // 转换数据格式为前端期望的格式
      const messages = resumeSubmissions.map((item: any) => ({
        id: `resume_${item.id}`,
        type: item.applicant_id === userId ? 'sent' : 'received',
        content: item.feedback || '简历投递',
        subject: `${item.job_title} - 简历投递`,
        sent_at: item.submitted_at,
        is_read: item.is_read,
        resume_id: item.id,
        job_post_id: item.job_post_id,
        applicant_id: item.applicant_id,
        company_contact_id: item.company_contact_id,
        applicant: {
          username: item.applicant_username,
          avatar: item.applicant_avatar
        },
        company: {
          name: item.company_name,
          logo: item.company_logo
        },
        feedback: item.feedback,
        reply_message: item.feedback
      }));

      return NextResponse.json(messages);

    } catch (dbError) {
      console.error('数据库查询失败:', dbError);
      return NextResponse.json({ error: '获取消息失败' }, { status: 500 });
    }

  } catch (error) {
    console.error('获取收件箱消息失败:', error);
    return NextResponse.json({ error: '服务器内部错误' }, { status: 500 });
  }
}

// POST 请求处理器 - 发送新消息
export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const token = request.headers.get('Authorization')?.replace('Bearer ', '');
    if (!token) {
      return NextResponse.json({ error: '未提供认证token' }, { status: 401 });
    }

    const decoded = verifyToken(token);
    if (!decoded) {
      return NextResponse.json({ error: '无效的token' }, { status: 401 });
    }

    const userId = decoded.userId;
    const { recipientId, content, messageType, resumeSubmissionId } = await request.json();

    if (!recipientId || !content) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    try {
      // 根据消息类型处理不同的逻辑
      if (messageType === 'resume_feedback' && resumeSubmissionId) {
        // 更新简历投递的反馈
        await UserModel.query(`
          UPDATE resume_submissions 
          SET feedback = ?, is_read = 1 
          WHERE id = ?
        `, [content, resumeSubmissionId]);

        return NextResponse.json({ 
          message: '反馈发送成功',
          success: true 
        });
      } else {
        // 这里可以扩展为通用的消息存储
        // 目前简化处理，直接返回成功
        return NextResponse.json({ 
          message: '消息发送成功',
          success: true 
        });
      }

    } catch (dbError) {
      console.error('数据库操作失败:', dbError);
      return NextResponse.json({ error: '发送消息失败' }, { status: 500 });
    }

  } catch (error) {
    console.error('发送消息失败:', error);
    return NextResponse.json({ error: '服务器内部错误' }, { status: 500 });
  }
} 